import Vue from 'vue';
import {Message, Loading} from 'element-ui';
import config from './config';
import metas from './metas';
import linkData from './data';

const serve = {
    /**
     * 处理post请求
     */
    doPost: (url, data) => {
        return new Promise((resolve, reject) => {
            Vue.axios.post(
                url,
                data,
                {
                    headers: {"X-Requested-With": 'xmlhttprequest'}
                }
            ).then((response) => {
                resolve(response);
            }).catch((error) => {
                Message({
                    message: error.message || '请求错误',
                    type: 'error'
                });
                reject(error);
            })
        })
    },
    /**
     * 加载弹框
     */
    doLoading: () => {
        return Loading.service({
            text: "加载中",
            spinner: "el-icon-loading",
            background: "rgba(255, 255, 255, 0.5)"
        })
    },
    /**
     * 处理get请求url参数
     * @param data
     * @returns {string}
     */
    getQueryParam: (data) => {
        let params = [];
        for (let key in data) {
            let newValue = key + '=' + data[key];
            params.push(newValue);
        }
        let newParam = params.join('&') + '&wxapp_id=' + config.wxapp_id;
        return "?" + newParam;
    },
    /**
     * 获取设备宽度
     * @returns {boolean}
     * @private
     */
    _isMobile() {
        const width = document.body.clientWidth;
        if (width <= 975) return true;
        return false;
    },
    /**
     * 获取请求url
     * @param apiKey
     * @param data
     * @param type
     * @returns {*}
     */
    handleGetUrl: (apiKey, data, type = '') => {
        const environment = config.environment;
        const s = config[environment].api[apiKey];
        const params = Object.assign({}, {s: s}, data);
        let newParams = serve.getQueryParam(params);
        let api = environment === 'development' ? s : '';
        let url = config[environment].root + api + newParams;
        if (type === 'cloudflare') {
            url = config[environment].contactRoot + api;
        }
        return url;
    },
    /**
     * 格式化html字符串
     * @param html
     * @returns {*}
     */
    unescape: (html) => {
        return html
            .replace(html ? /&(?!#?\w+;)/g : /&/g, '&amp;')
            .replace(/&lt;/g, "<")
            .replace(/&gt;/g, ">")
            .replace(/&quot;/g, "\"")
            .replace(/&#39;/g, "'")
            .replace(/nowrap/g, "normal")
            .replace(/&amp;nbsp;/g, " ");
    },
    /**
     * 替换span内容
     * @param html
     */
    handleReplaceSpan: (html) => {
        // console.log(html)
        // const domain = location.host;
        // const spanRex=/(<span style="font-size:16px" data-id="(.+)">.*?<\/span>)/g;
        // const rex=/<p\s*.*?>.*?<\/p>/g;
        // console.log(html.match(rex));
        // const pArray=html.match(rex);
        // for (let i=0;i<pArray.length;i++){
        //     pArray[i]=pArray[i].replace(spanRex,`<a target="_blank" href="http://${domain}/#/productDetail?id=$2">$1</a>`);
        // }
        // return pArray.join('');
        return html;
    },
    /**
     * 统一设置meta
     * @param key
     * @param linkKey
     * @returns {{meta: {name: string, content: *}[], title: *}|{meta: {name: string, content: string}[], title: string}}
     */
    handleSetMeta(key,linkKey='') {
        const config = metas[key];
        const linkItem=linkData[linkKey];
        const links=[];
        if (linkItem){
            for (let i=0;i<linkItem.length;i++){
                let item={ rel:"alternate", href: '', hreflang: 'default' };
                let newItem=Object.assign({},item,linkItem[i]);
                links.push(newItem);
            }
        }
        if (config) {
            return {
                title: config.title,
                meta: [
                    {name: 'description', content: config.description}
                ],
                link: links
            }
        } else {
            return {
                title: 'billingham',
                meta: [
                    {name: 'description', content: 'billingham'}
                ],
                link:links
            }
        }

    },
    /**
     * 获取index分组
     * @param realList
     * @param len
     * @returns {Array}
     */
    handleGetIndexList(realList,len=3){
        const indexList = [];
        let item = [];
        for (let i = 0; i < realList.length; i++) {
            item.push(i);
            if ((i + 1) % len === 0) {
                indexList.push(JSON.parse(JSON.stringify(item)));
                item = [];
            }
        }
        if (realList.length % len !== 0) {
            indexList.push(item);
        }
        return indexList;
    },
    /**
     * 获取轮播图的高度
     * @param width
     * @returns {number}
     */
    handleGetSlideHeight(width) {
        width = width > 1200 ? 1080 : width;
        let scale = 2173 / 700;
        let height = width / scale;
        return Math.floor(height);
    }
};
export default serve;
